import 'package:flutter/material.dart';

class ConstraintsWidget extends StatelessWidget {
  final dynamic width, height;
  final Widget? child;

  ConstraintsWidget({
    Key? key,
    this.width,
    this.height,
    this.child,
  }) : super(key: key);

  dynamic _lengthGenerator({
    required String type,
    required dynamic length,
    required BuildContext context,
    required BoxConstraints constraints,
  }) {
    if (length == null) {
      return null;
    } else if (length is num) {
      return length.toDouble();
    } else if (length is String) {
      RegExp percentExp = RegExp(r"%");
      RegExp vwExp = RegExp(r"vw");
      RegExp vhExp = RegExp(r"vh");
      Iterable<RegExpMatch> percentExpMatches = percentExp.allMatches(length);
      Iterable<RegExpMatch> vwExpMatches = vwExp.allMatches(length);
      Iterable<RegExpMatch> vhExpMatches = vhExp.allMatches(length);
      double k =
          double.parse(length.split('%')[0].split('vw')[0].split('vh')[0]) /
              100.0;
      double res = 0.0;
      if (percentExpMatches.length > 0) {
        if (type == 'width') {
          res = constraints.maxWidth * k;
        } else if (type == 'height') {
          res = constraints.maxHeight * k;
        }
      } else if (vwExpMatches.length > 0) {
        res = MediaQuery.of(context).size.width * k;
      } else if (vhExpMatches.length > 0) {
        res = MediaQuery.of(context).size.height * k;
      } else {
        res = 0.0;
      }
      return res;
    }
  }

  Widget _containerBuilder({
    required BuildContext context,
    required BoxConstraints constraints,
  }) {
    var _width = _lengthGenerator(
      type: 'width',
      length: this.width,
      context: context,
      constraints: constraints,
    );
    var _height = _lengthGenerator(
      type: 'height',
      length: this.height,
      context: context,
      constraints: constraints,
    );
    return Container(
      width: _width,
      height: _height,
      child: this.child,
    );
  }

  /// 但宽度和高度为绝对值时，可直接传[double]类型的值，当宽度和高度为百分比或者vw、vh时（根据屏幕可视宽高计算）
  /// 传入'xx%'、'xxvw'、'xxvh'字符串即可

  @override
  Widget build(BuildContext ctx) {
    return LayoutBuilder(builder: (context, constraints) {
      Widget child =
          _containerBuilder(context: context, constraints: constraints);
      return child;
    });
  }
}
